package com.itheima.reggie.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import com.itheima.reggie.common.R;
import com.itheima.reggie.service.OrderService;
import com.itheima.reggie.util.PayUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/pay")
public class PayController {

    @Autowired
    private OrderService orderService;


    @RequestMapping("/getPayURL")
    public R<String> getPayURL(String oid, String amount){
        //1.获取请求数据订单后和支付金额
        //2.统一下单：根据支付工具类使用订单号和支付金额生成预交易的地址
        String payUrl = PayUtils.createOrder(oid, 1);
        //3.将预交易地址存储在请求与域中
//        Map pay = new HashMap();
//        pay.put("oid",oid);
//        pay.put("amount",amount);
//        pay.put("payUrl",payUrl);
        //4.跳转支付页面
        return R.success(payUrl);
    }

    @RequestMapping(value = "/payNotify",produces = {"application/xml;charset=UTF-8"})
    public String payNotify(@RequestBody Map<String, String> map,HttpServletResponse response) throws IOException {
        try {
            PayUtils.checkResultCode(map);
        }catch (Exception e) {
            e.printStackTrace();
            log.info("用户支付失败");
        }
        log.info("用户已支付");
        //不报异常则用户支付成功，更新订单状态
        orderService.updateByWxMap(map);
        log.info("更新数据库成功");
        Map<String,String> resultMap = new HashMap<>();
        resultMap.put("return_code","SUCCESS");
        resultMap.put("return_msg","OK");
//        //把数据转换为xml的方式
        String xmlData = new XmlMapper().writeValueAsString(resultMap);
//        response.setContentType("application/xml;charset=utf-8");
//        response.getWriter().write(xmlData);
        return xmlData;
    }
}
